<template>
  <!-- <n-message-provider :max="1"> -->
  <n-card class="w-450px my-card">
    <h1 class="text-center">选择登录方式</h1>
    <n-form
      ref="formRef"
      :model="model"
      :rules="rules"
      :size="size"
      label-placement="top"
    >
      <n-form-item label="邮箱" path="userName">
        <n-input placeholder="请输入邮箱" v-model:value="model.userName" />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input
          placeholder="请输入密码"
          v-model:value="model.password"
          type="password"
        />
      </n-form-item>
      <div
        @click="isLogin = !isLogin"
        style="cursor: pointer"
        class="text-right block"
      >
        {{ isLogin ? "没有账号去注册" : "已有账号？去登录" }}
      </div>
      <n-form-item>
        <n-button class="w-100%" type="primary" @click="handleSubmit">{{
          isLogin ? "登录" : "注册"
        }}</n-button>
      </n-form-item>
    </n-form>
  </n-card>
  <!-- </n-message-provider> -->
</template>

<script setup>
// import { useMessage } from "naive-ui";
import { useUserStore } from "@/store/user";
import { commonApi } from "~/api";
const userStore = useUserStore();
const isLogin = ref(true);
const model = ref({
  userName: "",
  password: "",
});

const rules = ref({
  userName: [{ required: true, message: "请输入邮箱", trigger: ["blur"] }],
  password: [{ required: true, message: "请输入密码", trigger: ["blur"] }],
});
const size = ref("medium");
const formRef = ref(null);
const handleSubmit = async () => {
  if (!isLogin.value) {
    try {
      formRef.value.validate(async (errors) => {
        if (!errors) {
          const res = await commonApi("/api/register", "post", model.value);
          if (res.code === 10000) {
            alert("注册成功");
          } else {
            alert(res.msg);
          }
        }
      });
    } catch (error) {
      console.log("注册失败", error);
      alert("注册失败");
    }
  } else {
    try {
      formRef.value.validate(async (errors) => {
        if (!errors) {
          const res = await commonApi("/api/login", "post", {
            userName: model.value.userName,
            password: Number(model.value.password),
          });
          if (res.code === 10000) {
            alert("登录成功");
            // 存储用户信息
            userStore.setUserInfo(res.data.userName, res.data.token);
            // 登录成功后，跳转到首页
            navigateTo('/')
          } else {
            alert(res.msg);
          }
        }
      });
    } catch (error) {
      alert("登录失败");
    }
  }
};
</script>

<style>
.my-card {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}
</style>